/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package builder;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import persistence.DataReader;
import persistence.DataWriter;

/**
 *
 * @author Danielondon
 */
public class SimulationBuilderAgent extends Agent{
    
    private SimulationBuilderView view;
    DataReader fileReader;
    DataWriter fileWriter;
    
    @Override
    protected void setup() {
        String priceDataFile = this.verifyPriceDataFile();        
        this.view = new SimulationBuilderView(this, priceDataFile);
        this.view.showGui();
    }
    
    @Override
    protected void takeDown(){
        this.view.dispose();
    }

    /**
     * Sets the price data file
     * @param fileName
     * @return 
     */
    public String setPriceDataFile(String fileName) {
        String fileData = "Incorrect file";
        try {
            fileReader = new DataReader(fileName);                        
            DataWriter fileWriter = new DataWriter(DataWriter.MARKET_DATA_FILE, false);
            fileWriter.copyFile(fileReader.getFile());
            fileData = verifyPriceDataFile();
        } catch (Exception ex) {
            Logger.getLogger(SimulationBuilderAgent.class.getName()).log(Level.SEVERE, null, ex);  
            fileData +=  " : " + ex.getMessage();
        }
        
        return fileData;
    }
    
    /**
     * Verifies the DAta file
     * @return 
     */
    public String verifyPriceDataFile() {
        String fileName = DataWriter.MARKET_DATA_FILE;
        fileReader = null;
        try {
            fileReader = new DataReader(fileName);
        } catch (Exception ex) {
            return "File does not exist";
        }
        
        List<String []> data= new ArrayList();
        try {
            data = fileReader.getData();
        } catch (Exception ex) {
            return "Data can not be read from the file";
        }
        
        if (data.size() == 0)
            return "File contains no data";
            
        try {
            for (String[] d : data) {
                Double.parseDouble(d[DataWriter.PRICE_INDEX]);
            }
        } catch (Exception ex) {
            return "Data is in incorrect format";
        }
        
        return fileReader.getFile().toPath().toString();
    }    
}
